package com.example.sample.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.app.BaseActivity;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.RequiresApi;

public class RegisterNetworkCallbackActivity extends BaseActivity {

    private static final String TAG = RegisterNetworkCallbackActivity.class.getSimpleName();
    private Handler handler = new Handler();
    private TextView tv;
    private boolean open = true;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ConnectivityManager svc = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        svc.registerNetworkCallback(builder.build(), new Callback());

        ScrollView scrollView = new ScrollView(this);
        tv = new TextView(this);
        scrollView.addView(tv, -1, -2);
        setContentView(scrollView);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("asdfgh");
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                wifiManager.setWifiEnabled(open);
                addLog("setWifiEnabled " + open);
                open = !open;
                startTimer();
            }
        }, intentFilter);

        //startTimer();

        /*Toast.makeText(RegisterNetworkCallbackActivity.this, "崩不崩", Toast.LENGTH_SHORT).show();
        try{
            Thread.sleep(3000);
        }catch (Exception e){

        }*/
        int r = testReturnInTry();
        Log.i(TAG, "--return--" +r);

        Map<String, String> m = new HashMap<>();
        m.put("a", " 1");
        m.put("b", " 2");
        m.put("c", " 3");
        Log.i(TAG, m.toString());

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(new ComponentName("com.ny.mqttdemo", "com.ny.mqttdemo.MainActivity"));
        if (intent.resolveActivity(getPackageManager()) != null){
            startActivity(intent);
        }
    }

    private int testReturnInTry(){
        int i = 1;
        try{
            Log.i(TAG, "--return--");
            return i;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Log.i(TAG, "--finally--" + i);
            i = 0;
            Log.i(TAG, "--finally--" + i);
        }
        return -1;
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void startTimer(){
        Intent intent = new Intent("asdfgh");
        PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 5000, pi);
    }

    private void addLog(final String text){
        handler.post(new Runnable() {
            @Override
            public void run() {
                String src = tv.getText().toString();
                String dst = src + text + "\n";
                tv.setText(dst);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private class Callback extends ConnectivityManager.NetworkCallback{
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            addLog("onAvailable " + network);
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();
            addLog("onUnavailable");
        }

        @Override
        public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            addLog("onCapabilitiesChanged " + network);
        }

        @Override
        public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
            super.onLinkPropertiesChanged(network, linkProperties);
            addLog("onLinkPropertiesChanged " + network);
        }

        @Override
        public void onLosing(Network network, int maxMsToLive) {
            super.onLosing(network, maxMsToLive);
            addLog("onLosing " + network);
        }

        @Override
        public void onLost(Network network) {
            super.onLost(network);
            addLog("onLost " + network);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*new H(this).postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RegisterNetworkCallbackActivity.this, "崩不崩", Toast.LENGTH_SHORT).show();
            }
        }, 5000);*/
    }

    private static class H extends Handler{
        private Activity a;
        public H(Activity a){
            this.a = a;
        }
    }
}
